package com.soft.line.common;

import com.soft.line.util.exception.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @Description: 全局异常处理器 异常在此处拦截进行处理 不用再在dao service controller中处理
 *
 * @version: v1.0.0
 * @author: wpb
 * @date: 2020年3月6日 下午1:13:00
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
	public CommonResult<String> handleException(HttpRequestMethodNotSupportedException e) {
		log.error(e.getMessage(), e);
		return CommonResult.failed("不支持' " + e.getMethod() + "'请求");
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(RuntimeException.class)
	public CommonResult<String> notFount(RuntimeException e) {
		log.error("运行时异常:", e);
		return CommonResult.failed("服务器异常，请联系管理员");
	}

	/**
	 * 参数校验异常
	 */
	@ExceptionHandler({ MethodArgumentNotValidException.class })
	public CommonResult<String> handleParamsException(MethodArgumentNotValidException e) {
		String errorMsg = e.getBindingResult().getAllErrors().stream()
				.map(objectError -> ((FieldError) objectError).getDefaultMessage()).collect(Collectors.joining(","));
		log.error(errorMsg, e);
		return CommonResult.failed(errorMsg);
	}

	/**
	 * formdata参数校验异常
	 */
	@ExceptionHandler({ BindException.class })
	public CommonResult<String> handleFromParamsException(BindException e) {
		String errorMsg = e.getBindingResult().getAllErrors().stream()
				.map(objectError -> ((FieldError) objectError).getDefaultMessage()).collect(Collectors.joining(","));
		log.error(errorMsg, e);
		return CommonResult.failed(errorMsg);
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public CommonResult<String> handleException(Exception e) {
		log.error(e.getMessage(), e);
		return CommonResult.failed("服务器错误，请联系管理员");
	}

}
